package com.gupao.ldr.pattern.prototype.deep;

import java.io.*;
import java.util.Date;

/**
 * 齐天大圣模型(深克隆)
 */
public class QiTianDaSheng extends Monkey implements Cloneable,Serializable{

    private JinGuBang jinGuBang;

    public QiTianDaSheng() {
        this.setBirthday(new Date());
        this.jinGuBang=new JinGuBang();

    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public Object deepClone(){



        try {
            //内存中完成操作，对象读写，是通过字节码直接操作
            ByteArrayOutputStream bos=new ByteArrayOutputStream();
            ObjectOutputStream oos=new ObjectOutputStream(bos);
            oos.writeObject(this);


            ByteArrayInputStream bis=new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois=new ObjectInputStream(bis);
            //完整新对象，new出来一个对象
            QiTianDaSheng copy=(QiTianDaSheng)ois.readObject();
            copy.setBirthday(new Date());
            return copy;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    public static void main(String[] args) {
        QiTianDaSheng qiTianDaSheng=new QiTianDaSheng();
        qiTianDaSheng.jinGuBang.setHeight(10000);
        System.out.println(qiTianDaSheng.jinGuBang.getHeight());
        try {
            QiTianDaSheng obj = (QiTianDaSheng) qiTianDaSheng.deepClone();
            System.out.println(obj.jinGuBang.getHeight());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
